<?php
include('../resource/db/db.php');
session_start();

if (!isset($_COOKIE['role']) || $_COOKIE['role'] != 'admin') {
    header("Location: ../main/login.php");
    exit();
}

$card_id = $_GET['card_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $_POST['title'];
    $content = $_POST['content'];
    $card_type = $_POST['card_type'];

    $sql = "UPDATE cards SET title=?, content=?, card_type=?, updated_at=NOW() WHERE card_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssi", $title, $content, $card_type, $card_id);
    
    if ($stmt->execute()) {
        echo "卡片更新成功！";
        header("Location: manage-cards.php");
        exit();
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $stmt->close();
} else {
    $sql = "SELECT * FROM cards WHERE card_id=? AND is_deleted=FALSE";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $card_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $card = $result->fetch_assoc();
    $stmt->close();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>编辑卡片</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
</head>
<body>
    <?php include('../resource/navbar.php'); ?>
    <div class="container">
        <h2>编辑卡片</h2>
        <?php if ($card): ?>
            <form method="post" action="">
                <div class="form-group">
                    <label for="title">标题:</label> 
                    <input type="text" id="title" name="title" class="form-control" value="<?php echo $card['title']; ?>" required>
                </div>
                <div class="form-group">
                    <label for="content">内容:</label>
                    <textarea id="content" name="content" class="form-control" required><?php echo $card['content']; ?></textarea>
                </div>
                <div class="form-group">
                    <label for="card_type">类型:</label>
                    <select id="card_type" name="card_type" class="form-control">
                        <option value="video" <?php if ($card['card_type'] == 'video') echo 'selected'; ?>>视频</option>
                        <option value="image" <?php if ($card['card_type'] == 'image') echo 'selected'; ?>>图片</option>
                        <option value="text" <?php if ($card['card_type'] == 'text') echo 'selected'; ?>>文字</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">更新</button>
            </form>
        <?php else: ?>
            <p>卡片不存在或已被删除。</p>
        <?php endif; ?>
    </div>
</body>
</html>

